package com.cloudbroker.bcs.platform.dav.middle.bizservice.impl;

import com.cloudbroker.bcs.common.configure.ConfigUtil;
import com.cloudbroker.bcs.common.util.*;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes.ChatRoomErr;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes.ClientErr;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.LiveBizService;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.result.*;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.vo.CCLiveListForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.vo.BrokerIdListQryForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.vo.ChatTopicListQryForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.vo.TenantKeyListQryForm;
import com.cloudbroker.bcs.platform.dav.common.config.ConfigValues;
import com.cloudbroker.bcs.platform.dav.common.util.SessionHelper;
import com.cloudbroker.bcs.platform.dav.middle.context.HSBCPSBizDataContext;
import com.cloudbroker.bcs.platform.dav.middle.entity.*;
import com.cloudbroker.bcs.platform.dav.middle.entityview.BrokerUserIdListView;
import com.cloudbroker.bcs.platform.dav.middle.entityview.CompanyBrokerListView;
import com.cloudbroker.bcs.platform.dav.middle.entityview.HistoryInvestView;
import com.cloudbroker.bcs.platform.dav.middle.entityview.LiveInvestView;
import com.cloudbroker.bcs.platform.dav.middle.extservice.cc.CCService;
import com.cloudbroker.bcs.platform.dav.middle.extservice.ltb.LTBService;
import com.cloudbroker.bcs.platform.dav.middle.service.*;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.text.ParseException;
import java.util.*;

/**
 * Created by lnq on 2016/10/26.
 */
@Service
public class LiveBizServiceImpl implements LiveBizService {
    @Resource
    private ChatRoomService chatRoomService;
    @Resource
    private TenantService tenantService;
    @Resource
    private CCService ccService;
    @Resource
    private ChatTopicService chatTopicService;
    @Resource
    private BrokerService brokerService;
    @Resource
    private CustomerBrokerFollowService customerBrokerFollowService;
    @Resource
    private LTBService ltbService;
    @Resource
    private ChatMsgService chatMsgService;
    
    @Override
    public LiveInvestListResult liveInvestList(TenantKeyListQryForm param) {
        String position_str = param.getPosition_str();
        Integer request_num = ValueUtil.getInt(param.getRequest_num(), ConfigValues.getRequestNum());
        Integer tenant_id = HSBCPSBizDataContext.getTenantId();
        Customer customer = HSBCPSBizDataContext.getCustomerNoException();
        String customer_id = null;
        if (customer != null) {
            customer_id = ValueUtil.getString(customer.getCustomer_id());
        }
        List<LiveInvestView> liveInvestViews = chatRoomService.liveInvestList(customer_id, position_str,
                request_num);
        LiveInvestListResult result = new LiveInvestListResult();
        ArrayList<LiveInvestListData> liveInvestListDatas = new ArrayList<>();
        List<Long> broekerIds = new ArrayList<>();
        for (LiveInvestView liveInvestView : liveInvestViews) {
            LiveInvestListData listData = new LiveInvestListData();
            listData.setBroker_id(liveInvestView.getBroker_id());
            broekerIds.add(ValueUtil.getLong(liveInvestView.getBroker_id()));
            listData.setBroker_name(liveInvestView.getBroker_name());
            listData.setBroker_avatar(liveInvestView.getBroker_avatar());
            listData.setLive_broadcast_flag(liveInvestView.getLive_broadcast_flag());
            listData.setLive_broadcast_title(liveInvestView.getLive_broadcast_title());
            listData.setRoom_status(liveInvestView.getRoom_status());
            listData.setPosition_str(liveInvestView.getPosition_str());
            listData.setBroker_key(liveInvestView.getBroker_key());
            listData.setInvitation_code(liveInvestView.getInvitation_code());
            if (liveInvestView.getFollow_type() == 0) {
                listData.setFollow_type(liveInvestView.getFollow_type());
            } else {
                listData.setFollow_type(1);
            }
            listData.setCc_room_id(liveInvestView.getCc_room_id());
            String brokerId = liveInvestView.getBroker_id();
            Set<String> newFansList = SessionHelper.getInstance().getNewOnlineList(brokerId);
            Set<String> oldFansList = SessionHelper.getInstance().getOldOnlineList(brokerId);
            if (newFansList != null) {
                newFansList.addAll(oldFansList);
                listData.setOnline_num(newFansList.size());
            }
            liveInvestListDatas.add(listData);
        }
        List<ChatTopic> chatTopicList = chatTopicService.getTopicListByBroker(broekerIds,tenant_id);
        for(int i = 0;i<liveInvestListDatas.size();i++){
            for(int j=0;j<chatTopicList.size();j++){
                if(ValueUtil.getLong(liveInvestListDatas.get(i).getBroker_id()) == chatTopicList.get(j).getCreate_by()){
                    liveInvestListDatas.get(i).setTopic(chatTopicList.get(j).getTopic_title());
                }
            }
        }
        result.setData_list(liveInvestListDatas);
        return VOUtil.setSuccessResult(result);
    }
    
    @Override
    public HistoryInvestList historyLiveInvestList(BrokerIdListQryForm param) {
        HistoryInvestList result = new HistoryInvestList();
        String position_str = param.getPosition_str();
        Integer request_num = ValueUtil.getInt(param.getRequest_num(), ConfigValues.getRequestNum());
        Broker b = brokerService.getByKey(param.getBroker_key());
        if (null == b) {
            return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, HistoryInvestList.class);
        }
        Long broker_id = b.getBroker_id();
        Integer tenant_id = b.getTenant_id();
        HSBCPSBizDataContext.setTenantId(tenant_id);
        int cclive_visible = ConfigUtil.getTenantConfig("tenant" + ValueUtil.getString(tenant_id)).get("is.cclive.visible", true) == true ? 1 : 0;
        ChatRoom cr = chatRoomService.getChatRoomByBrokerId(broker_id);
        if (null == cr) {
            return VOUtil.genErrorResult(ChatRoomErr.NO_SUCH_CHAT_ROOM, HistoryInvestList.class);
        }
        String room_id = cr.getCc_room_id();
        Integer room_status = cr.getRoom_status();
        if(null == room_status){
            room_status = 0;
        }
        result.setRoom_status(room_status);
        result.setLive_url(cr.getLive_broadcast_url());
        Integer live_flag = cr.getLive_broadcast_flag();
        if(null == live_flag){
            live_flag = 0;
        }
        result.setLive_flag(live_flag);
        String current_topic = "";
        Long topic_id = null;
        // 当前话题
        ChatTopic topic = chatTopicService.getTopicTitle(broker_id);        
        if (null != topic) {
            current_topic = topic.getTopic_title();
            topic_id = topic.getTopic_id();
        }
        result.setTopic_id(topic_id);
        result.setTopic(current_topic);
        result.setCc_room_id(room_id);
        //处理定位串
        if("0".equals(position_str)){
            position_str = null;
        }else{
            Date date = new Date(Long.parseLong(position_str));
            position_str = DateTimeUtil.toString(date, DateTimeUtil.FORMAT_YYYYMMDDHHMMSS);
        }
        List<HistoryInvestView> res_list = new ArrayList<HistoryInvestView>();
        //文字直播列表
        List<ChatTopic> wordlist = chatTopicService.getHistoryList(broker_id, tenant_id, position_str, request_num);
        //添加文字直播列表进结果列表
        if(null != wordlist && wordlist.size() > 0){
            for (ChatTopic ct : wordlist) {
                //过滤当前直播
                if(null != topic_id){
                    if(topic_id.equals(ct.getTopic_id())){
                        continue;
                    }
                }
                HistoryInvestView view = new HistoryInvestView();
                view.setBroker_avatar(b.getBroker_avatar());
                view.setBroker_name(b.getBroker_name());
                view.setChat_topic(ct.getTopic_title());
                view.setLive_type("0");
                view.setPosition_str(Long.toString(ct.getCreate_time().getTime()));
                view.setStart_time(DateTimeUtil.toString(ct.getCreate_time(), DateTimeUtil.FORMAT_YYYYMMDDHHMMSS));
                res_list.add(view);
            }
        }
        //视频直播列表,视频直播可见才显示
        if(1 == cclive_visible){
            CCLiveListForm ccfrom = new CCLiveListForm();
            ccfrom.setRoom_id(room_id);
            ccfrom.setStart_time(position_str);
            ccfrom.setPage_num(param.getRequest_num());
            CCHistoryList cc_res = ccService.funcGetCCListByID(ccfrom);
            List<CCHistoryListData> reslist = cc_res.getData_list();
            //添加视频直播列表进结果列表
            if(null != reslist && reslist.size() > 0){
                for (CCHistoryListData data : reslist) {
                    HistoryInvestView view = new HistoryInvestView();
                    view.setBroker_avatar(b.getBroker_avatar());
                    view.setBroker_name(b.getBroker_name());
                    view.setLive_type("1");
                    view.setLive_url(data.getReplayUrl());
                    view.setStart_time(data.getStartTime());
                    try {
                      Date d = DateTimeUtil.toDate(data.getStartTime());
                      view.setPosition_str(Long.toString(d.getTime()));
                    } catch (ParseException e) {
                    }                
                    res_list.add(view);
                }
            }    
        }     
        //处理结果列表,按时间倒序排序,返回请求数量
        Collections.sort(res_list, new Comparator<HistoryInvestView>() {
            public int compare(HistoryInvestView v1, HistoryInvestView v2) {
                //按照时间顺序倒序排序
                Long time1 = new Date().getTime();
                Long time2 = time1;
                try {
                    time1 = DateTimeUtil.toDate(v1.getStart_time()).getTime();
                    time2 = DateTimeUtil.toDate(v2.getStart_time()).getTime();
                } catch (ParseException e) {
                }
                if (time1 > time2) {
                    return -1;
                }
                if (time1.equals(time2)) {
                    return 0;
                }
                return 1;
            }
        });
        if(request_num < res_list.size()){
            res_list = res_list.subList(0, request_num);
        }        
        result.newDataList().addAll(res_list);
        return VOUtil.setSuccessResult(result);
    }

    @Override
    public CompanyBrokerList funcCompanyBrokerList(TenantKeyListQryForm form) {
        CompanyBrokerList res = new CompanyBrokerList();
        String tenant_key = form.getTenant_key();
        int position_str = Integer.parseInt(form.getPosition_str());
        int request_num = Integer.parseInt(form.getRequest_num());
        Tenant t = tenantService.getByKey(tenant_key);
        if(null == t){
            return VOUtil.genErrorResult(ClientErr.TENANT_NOT_EXIST, CompanyBrokerList.class);
        }
        Integer tenant_id = t.getTenant_id();
        HSBCPSBizDataContext.setTenantId(tenant_id);
        int cclive_visible = ConfigUtil.getTenantConfig("tenant" + ValueUtil.getString(tenant_id)).get("is.cclive.visible", true) == true ? 1 : 0;
        List<CompanyBrokerListView> view = new ArrayList<CompanyBrokerListView>();
        List<BrokerUserIdListView> broker_list = brokerService.getBrokerUserIdList();
        if(null != broker_list && broker_list.size() > 0){
            for(BrokerUserIdListView b : broker_list){
                CompanyBrokerListView data = new CompanyBrokerListView();
                Long broker_id = b.getBroker_id();
                int live_invest_num = chatTopicService.countByBrokerId(broker_id, tenant_id);
                data.setBroker_id(broker_id);
                data.setBroker_avatar(b.getBroker_avatar());
                data.setBroker_name(b.getBroker_name());
                data.setBroker_key(b.getBroker_key());
                data.setUser_id(b.getUser_id());
                if(1 == cclive_visible){
                    ChatRoom c = chatRoomService.getChatRoomByBrokerId(broker_id);
                    if(null != c && c.getCc_room_id() != null){
                        CCLiveListForm ccfrom = new CCLiveListForm();
                        ccfrom.setRoom_id(c.getCc_room_id());
                        CCHistoryList cc_res = ccService.funcGetCCListByID(ccfrom);
                        if(!StringUtil.isBlank(cc_res.getCount())){
                            int count = Integer.parseInt(cc_res.getCount());
                            live_invest_num += count;
                        }                    
                    } 
                }
                data.setLive_invest_num(live_invest_num);
                view.add(data);
            }
        }
        //处理结果集，按直播数倒序排序
        Collections.sort(view, new Comparator<CompanyBrokerListView>() {
            public int compare(CompanyBrokerListView v1, CompanyBrokerListView v2) {
                //按照时间顺序倒序排序
                int num1 = v1.getLive_invest_num();
                int num2 = v2.getLive_invest_num();
                if (num1 > num2) {
                    return -1;
                }
                if (num1 == num2) {
                    return 0;
                }
                return 1;
            }
        });
        //设置定位串
        for(int i=0,j=view.size();i<j;i++){
            CompanyBrokerListView v = view.get(i);
            v.setPosition_str(i+1+"");
        }
        int begin_index = position_str;
        int end_index = position_str + request_num;
        //截取请求数量列表
        if(begin_index >= view.size()){
            //请求开始数量超过size返回空
            return VOUtil.setSuccessResult(res);
        }
        if(end_index >= view.size()){
            end_index = view.size();
        }
        view = view.subList(begin_index, end_index);
        res.newDataList().addAll(view);
        return VOUtil.setSuccessResult(res);
    }

    @Override
    public ChattopicQueryList funcChattopicList(ChatTopicListQryForm form) {
        String tenant_key = form.getTenant_key();
        Tenant tenant = tenantService.getByKey(tenant_key);
        if(null == tenant){
            return VOUtil.genErrorResult(ClientErr.TENANT_NOT_EXIST, ChattopicQueryList.class);
        }
        Integer tenant_id = tenant.getTenant_id();
        HSBCPSBizDataContext.setTenantId(tenant_id);
        List<ChatTopic> chatTopicList = chatTopicService.getByTenant(tenant_id);
        List<Long> brokerIds = null;
        ChattopicQueryList chattopicQueryList = new ChattopicQueryList();
        List<ChattopicQueryListData> resultList = new ArrayList<>();
        Integer online_num = -1;
        Integer his_chatmsg_num = 0;
        Integer request_num = 3;
        if (chatTopicList != null && !chatTopicList.isEmpty()) {
            brokerIds = new ArrayList<>();
            for (ChatTopic chatTopic : chatTopicList) {
                ChattopicQueryListData chattopicQueryListData = new ChattopicQueryListData();
                Long brokerId = chatTopic.getCreate_by();
                brokerIds.add(brokerId);
                Broker broker = brokerService.getById(brokerId, tenant_id);
                ChatRoom chatRoom = chatRoomService.getChatRoomByBrokerId(brokerId);
                if (chatRoom == null) {
                    return VOUtil.genErrorResult(ChatRoomErr.NO_SUCH_CHAT_ROOM, ChattopicQueryList.class);
                }
                online_num = setOnlineNum(online_num, brokerId, chatRoom);
                his_chatmsg_num = chatMsgService.countByTopic(chatTopic.getTopic_id(), tenant_id);
                chattopicQueryListData.setBroker_id(broker.getBroker_id());
                chattopicQueryListData.setBroker_avatar(broker.getBroker_avatar());
                chattopicQueryListData.setBroker_name(broker.getBroker_name());
                chattopicQueryListData.setBroker_key(broker.getBroker_key());
                chattopicQueryListData.setStart_time(DateUtil.dateToStr(chatTopic.getCreate_time(), DateUtil.YYYY_MM_DD_HH_MM_SS));
                chattopicQueryListData.setChat_topic(chatTopic.getTopic_title());
                chattopicQueryListData.setTopic_id(chatTopic.getTopic_id());
                chattopicQueryListData.setOnline_fans_num(online_num);
                chattopicQueryListData.setRoom_status(chatRoom.getRoom_status());
                chattopicQueryListData.setHis_chatmsg_num(his_chatmsg_num);
                resultList.add(chattopicQueryListData);
            }
            request_num = 3 - chatTopicList.size();
        }

        List<ChatMsg> chatMsgList = null;
        chatMsgList = chatMsgService.getByTenant(brokerIds, tenant_id, request_num);
        if (chatMsgList != null) {
            for (ChatMsg chatMsg : chatMsgList) {
                ChattopicQueryListData chattopicQueryListData = new ChattopicQueryListData();
                Long brokerId = chatMsg.getBroker_id();
                Broker broker = brokerService.getById(brokerId, tenant_id);
                ChatRoom chatRoom = chatRoomService.getChatRoomByBrokerId(brokerId);
                if (chatRoom == null) {
                    return VOUtil.genErrorResult(ChatRoomErr.NO_SUCH_CHAT_ROOM, ChattopicQueryList.class);
                }
                online_num = setOnlineNum(online_num, brokerId, chatRoom);
                String sendTime = chatMsg.getSend_time();
                String start_time = sendTime.substring(0, 10) + " 00:00:00";
                String end_time = sendTime.substring(0, 10) + " 23:59:59";
                his_chatmsg_num = chatMsgService.countByBroker(brokerId, tenant_id, start_time, end_time);
                ChatMsg chatMsg1 = chatMsgService.getByBroker(brokerId, tenant_id, start_time, end_time);
                chattopicQueryListData.setBroker_id(broker.getBroker_id());
                chattopicQueryListData.setBroker_avatar(broker.getBroker_avatar());
                chattopicQueryListData.setBroker_name(broker.getBroker_name());
                chattopicQueryListData.setBroker_key(broker.getBroker_key());
                chattopicQueryListData.setStart_time(chatMsg1.getSend_time().substring(0,19));
                chattopicQueryListData.setOnline_fans_num(online_num);
                chattopicQueryListData.setRoom_status(chatRoom.getRoom_status());
                chattopicQueryListData.setHis_chatmsg_num(his_chatmsg_num);
                resultList.add(chattopicQueryListData);
            }
        }
        chattopicQueryList.newDataList().addAll(resultList);
        return VOUtil.setSuccessResult(chattopicQueryList);
    }

    private Integer setOnlineNum(Integer online_num, Long brokerId, ChatRoom chatRoom) {
        Integer show_flag = ValueUtil.getIntObj(chatRoom.getShow_person_num_flag(),
                ConfigValues.ONLINE_NUM_SHOW_FLAG);
        Integer show_threshold = ValueUtil.getIntObj(chatRoom.getShow_person_num_threshold(),
                ConfigValues.ONLINE_NUM_SHOW_THRESHOLD);
         /*不显示，返回-1*/
        if (show_flag.equals(1)) {
            Set<String> newFansList = SessionHelper.getInstance().getNewOnlineList(String.valueOf(brokerId));
            Set<String> oldFansList = SessionHelper.getInstance().getOldOnlineList(String.valueOf(brokerId));
            newFansList.addAll(oldFansList);
        /*小于阈值，返回-1*/
            online_num = newFansList.size() <= show_threshold ? -1 : newFansList.size();
        }
        return online_num;
    }
}
